package main

import (
	"bufio"
	"fmt"
	"io"
	"strconv"
	"strings"
)

/**
实现斐波那契数列
*/

// 斐波那契数列规则  1 , 1 , 2 , 3 , 5 , 8 , 13 , 21  后个数是前2个数之和
func FibonacciGenerator() intGen{
	first, second := 0, 1
	return func() int {
		first, second = second, first+second
		return first
	}
}

/**
步骤一：定义一个类型
 */
type intGen func() int

/**
步骤二：为intGen 实现Reader接口
 */
func (gen intGen) Read(p []byte) (n int, err error)  {
	// 产生下一个元素
	nextElement := gen()
	if nextElement > 1000000 {
		return 0,io.EOF
	}
	strElement := strconv.Itoa(nextElement) + "\n"
	return strings.NewReader(strElement).Read(p)
}

func printlnReaderFibonacci(reader io.Reader)  {
	br := bufio.NewScanner(reader)
	for br.Scan()  {
		fmt.Println(br.Text())
	}
}

func main() {

	// printFibonacci()

	printlnReaderFibonacci(FibonacciGenerator())
}

/**
打印 斐波那契数列
 */
func printFibonacci() {
	generator := FibonacciGenerator()
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
	fmt.Println(generator())
}
